package com.dq.mail.interceptor;

import cn.hutool.core.bean.BeanUtil;
import com.dq.mail.entity.User;
import com.dq.mail.utils.RedisConstants;
import com.dq.mail.utils.ThreadUserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName: RefreshTokenInterceptor
 * @Description:
 * @Author: app-backend-public_小强 (QQ:2680825683)
 * @Since: 2023/3/3 17:32
 */
@Slf4j
public class RefreshTokenInterceptor implements HandlerInterceptor {
    //Spring IOC 注入
    private StringRedisTemplate stringRedisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    /**
     * 拦截请求 刷新redis缓存实现用户持久登录
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("authorization");
        String requestURI = request.getRequestURI();
        log.debug("ip:{}===>请求后台Api的接口为:{}", request.getRemoteAddr(), requestURI);
        if (StringUtils.isEmpty(token)) {
            return true; //如果没有token直接放行
        }
        Map<Object, Object> map = stringRedisTemplate.opsForHash().entries(RedisConstants.LOGIN_USER_KEY + token);
        //401 用户过期了
        if (map.isEmpty()) {
            response.setStatus(401);
            return false;
        }
        User user = BeanUtil.fillBeanWithMap(map, new User(), false);
        ThreadUserHolder.saveUser(user);
        stringRedisTemplate.expire(RedisConstants.LOGIN_USER_KEY + token, RedisConstants.LOGIN_USER_TTL, TimeUnit.MINUTES);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadUserHolder.removeUser(); //删除 value索引
    }
}
